<?php
class TemplateLoader
{
	var $loadedFile;
	var $lg;
	var $noBlocks = 5;
	var $blockDS;

	var $showEdit = true;
	var $crtBlockId = 0;
	
	var $inhibitHref = true;
	
	var $newsId = 1;
	
	function __construct($file, $lg='en',$news='1')
	{
		$this->newsId = $news;
		
		$this->campaignId = $this->loadedFile = $file;
		$this->lg = $lg;
		$row = Model::getNews($this->newsId,$this->lg);
		if(!$row) $this->noBlocks = 5;
		else 
		{
			$temp = $row['displayIndex'];
			$this->crtBlockId = $temp;
			$this->noBlocks =  $temp;
		}
	
	}


	function showTemplate()
	{
			
			
		$row = Model::getNews($this->newsId,$this->lg);
		$detail = Model::getNewsDetails($this->newsId);
		
			if(!$row || $this->noBlocks < $row['displayIndex'])
			{
				$content = new HTML("index_$this->lg.html","APPDATA/CAMPAIGNS/$this->loadedFile");// ../theme1/index.h
				$content -> set_var("BLOCKS", $this->loadModules());
					// $content -> set_var("FIN",$fin_theme1 );
				// $content -> set_var("BEGIN", $begin_theme1);
		
				// $newsDetail = Model::getNewsDetails($this->newsId);
				// $themeNews = $newsDetail['themeId'];
				// $content = new HTML("{$themeNews}");
				// $content -> set_var("BLOCKS", $this->loadModules());
				//embedd morph fields
				$html = utf8_encode($content -> gen());
				// $html =$content -> gen();
				

			}
			else
			{
				$content = new HTML("index_$this->lg.html","APPDATA/CAMPAIGNS/$this->loadedFile");
				$content_temp = $row['content'];
				// if ($detail['themeId'] == 1)
				// $place = stripos($content_temp,' </td><td width="10"></td>');
				// elseif ($detail['themeId'] == 2)
				// $place = stripos($content_temp," <font class=\"normalText\" onclick='morphField(this,\"\",\"\",event)' color=\"#000000\" face=\"Verdana\" size=\"1\">");
				// elseif ($detail['themeId'] == 4)
				// $place = stripos($content_temp,"<br><font class=\"normalText\" onclick='morphField(this,\"\",\"\",event)' color=\"#000000\" face=\"Verdana\" size=\"1\">");
				// elseif ($detail['themeId'] == 5)
				// $place = stripos($content_temp,"</td><td id=\"end\" name=\"end\" width=\"10\">");
				// elseif ($detail['themeId'] == 3 || $detail['themeId'] == 29 )
				// $place = stripos($content_temp,"<tr id=\"end\">");
				// elseif ($detail['themeId'] == 6)
				// $place = stripos($content_temp,"<table id=\"endOfBlock\" width=\"788\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">");
				// elseif ($detail['themeId'] == 31)
				$place = stripos($content_temp,"<!--- FOOTER --->");
				
				// else
				// $place = stripos($content_temp,'<td valign="middle" align="center" bgcolor="#645D57" height="130">');
				
				$content_temp = substr_replace($content_temp,utf8_encode($this->loadModules()), $place,0);
				// $content -> set_var("BEGIN", $content_temp);
				// $content -> set_var("BLOCKS", $this->loadModules());
				// $content -> set_var("FIN",$fin_theme1 );
				// $html = $content -> gen();
				$html =$content_temp ;
			}
		
	
		$html = str_replace("class=\"normalText\"", "class='normalText' onclick='morphField(this,\"\",\"\",event)'", $html); 
		// $html = str_replace("<font", "<font onclick='morphField(this,\"\",\"\",event)'", $html); 
		// $html = str_replace("<p", "<p onClick='morphField(this)'", $html); 
		$html = str_replace("<span", "<span onClick='morphField(this)'", $html); 
		$html = str_replace("<img", "<img onClick='morphImage(this, event)'", $html); 
		$html = str_replace("title=\"linkOfText\"", "title='linkOfText' onClick='morphLinkOfText(this,event)'", $html); 
		// $html = str_replace("id='description'", "id='description' onclick='editHTML(this,event)'", $html); 
		// $html = str_replace("id='description2'", "id='description2' onclick='editHTML(this,event)'", $html);
		$html = str_replace("title=\"videoBlock\"", "title='videoBlock' onClick='morphLinkOfVideo(this,event)'", $html); 
		$html = str_replace("none", "block", $html);
					if ($this->inhibitHref)
				$html = str_replace("href", "hreflang", $html);
		
		
		
		return $html;
	}


	function loadHotels()
	{
		$row = Model::getNews($this->newsId,$this->lg);
		if (!$row || $this->noBlocks < $row['displayIndex'])
		{
			$this->crtBlockId = 0;
			// provisional
			for($i=0;$i<$this->noBlocks;$i++)
			$this->hotelList[] =  'Pt-Avenida-Palace';
			// $this->hotelList[] =  'Pt-Altis-Avenida';
			// $this->hotelList[] =  'S-Pt-Avenida-Praia';
		}
		else
		{
			$temp = $this->noBlocks-$row['displayIndex'];
			for($i=0;$i<$temp;$i++)
			$this->hotelList[] =  'Pt-Avenida-Palace';
		}
}

	function loadModules()
	{
		//for each hotel in the list, create one block
		
		
			
		if(!$this->hotelList) $buildUp='';
		else
		{
			foreach ($this->hotelList as $fbName)
			{
				$buildUp .= $this->buildOneModule($fbName);
			}
		}


		return $buildUp;

	}


	function buildOneModule($fbName)
	{
		$template = new HTML("block1.html","APPDATA/CAMPAIGNS/$this->loadedFile/MODULES/");
		$_SESSION['FBCMS']['blocks'][++$this->crtBlockId]['internalVars'] = $template -> internalVars;
		$template -> set_var("HOTEL_NAME", $fbName);


		if ($this->showEdit)
		{
			$template -> set_var("__EDIT", "id='TR_{$this->crtBlockId}' onClick='editBlock(\"{$this->crtBlockId}\", event)'");
			$template -> set_var("NUMERO", "{$this->crtBlockId}");
		}
		else
			$template -> set_var("EDIT", "");
		return $template -> gen();
	}


	static function listCampaigns($userId=1)
	{
		$list = scandir("APPDATA/CAMPAIGNS/");
		foreach ($list as $one_element)
		{
			if ($one_element == '.' || $one_element == '..')
				continue;
			else
				$collected[] = $one_element;
		}

		if (is_array($collected))
		{
			$campaigns = Array();
			foreach ($collected as $one_id)
			{
				$campaigns[$one_id] = Model::getCampaignDetails($one_id, $userId);
			}
		}
		else
		{
			return false;
		}


		//lookup more info in the database

		return $campaigns;
	}


	public function buildNewsList($source,$nowEditing)
	{
		$flag = 0;
		if (!is_array($source))
			return false;

		$list = "<ul>";
		foreach ($source as $newsId => $details)
		{
			$linkLg = Model::getNewsAttributes($newsId,'lg');
			if(is_array($linkLg)) $languageOfNews = $linkLg[1]['attValue'];
			else $languageOfNews = $linkLg['attValue'];
			if( $details['name'] != $nowEditing)
			{
				$flag = 1;
				// $list .= "<li><a href='?campaignId={$this->campaignId}&newsId=$newsId&language=$languageOfNews' class='menu_links'>{$details['name']}</a></li><br/>";
				$list .= "<li><a href='javascript:void(0);' class='menu_links' onclick='linkOfNews(\"{$this->campaignId}\",\"$newsId\",\"$languageOfNews\")'>{$details['name']}</a></li><br/>";
			}
		}
		if ($flag == 0) $list .= "<strong>None</strong>";
		$list .= "</ul>";

		return $list;
	}

	public function buildCampaignList($source)
	{
		if (!is_array($source))
			return false;

		$list = "<ul>";
		foreach ($source as $campaignId => $details)
		{
			$list .= "<li><a href='?campaignId=$campaignId&newsId=1&language={$this->lg}'>{$details['name']}</a></li>";
		}
		$list .= "</ul>";

		return $list;
	}




	static function buildListOfTemplates($list) //must be changed to dislpay news inside campaign
	{
		if (!is_array($list))
			return "";

		$listHTML = "<ul class='m_ul'>";
		foreach ($list as $one_proj)
		{
			$listHTML .= "<li>
						<span>$one_proj</span>";

			//find index_{LG}.html filename
			$lg = self::findLgVersions($one_proj);
			if ($lg)
			{
				$lgGroup = "<ul style='margin-bottom: 10px'>";
				foreach ($lg as $one_language)
				{
					$lgGroup .= 
						"<li>
							<a href='javascript:void(0)' onClick='loadProj(\"$one_proj\",\"$one_language\")'>$one_language</a>
						</li>";
				}
				$lgGroup .= "</ul>";

				$listHTML .= $lgGroup;
			}
			else
				$lgGroup = "";

			$listHTML .= "</li>";
		}
		$listHTML .= "</ul>";

		return $listHTML;
	}


	static function findLgVersions($directory)
	{
		$files = scandir("APPDATA/CAMPAIGNS/$directory/");
		foreach ($files as $one_element)
		{
			if ($one_element == '.' || $one_element == '..')
				continue;
			elseif(strpos($one_element, ".html")!==false)
				$collected[] = $one_element;
		}

		if (!is_array($collected))
			return false;

		foreach ($collected as $html_files)
		{
			//get language stuff
			$rem1 = str_replace("index_", "", strtolower($html_files));
			$rem2 = str_replace(".html", "", strtolower($rem1));
			$collectLg[] = $rem2;
		}

		return $collectLg;
	}


	static function buildForm($fields,$number)
	{
		global $DESC, $TYPES, $TYPES_SH;

		if (!is_array($fields))
			return "nothing to build";
		
		foreach ($fields as $meta_var)
		{
			$meta_var = str_replace("{","",str_replace("}","",$meta_var));
			if ($meta_var != "IMG_1__SRC" && $meta_var != "IMG_1__HREF")
			{
				list($prefix, $suffix) = explode("__", $meta_var);

				//add predefined description for the meta vars that have a suffix
				if ($suffix && $prefix)
				{
					if (isset($DESC[$suffix]))
						$collectedVars[$meta_var]['desc'] = str_replace("$1", $prefix, $DESC[$suffix]);
					else
						$collectedVars[$meta_var]['desc'] = $meta_var;

					if (isset($TYPES[$suffix]))
						$collectedVars[$meta_var]['type'] = str_replace("$1", $prefix, str_replace("$2", $existingValue, $TYPES[$suffix]));
					else
						$collectedVars[$meta_var]['type'] = "";

					$collectedVars[$meta_var]['typeSh'] = $TYPES_SH[$suffix];
				}
			}
			
		}


		$ret = "<div style='overflow: auto; margin-top: 10px;'>";
		foreach ($collectedVars as $meta_var => $details)
		{
			if ($details['typeSh']=='file')
				$MARGIN_RIGHT = "20";
			else
				$MARGIN_RIGHT = "3";

			$ret .= "<div class='edit_ib'>
					<div style='float:left; padding-top:2px; padding-left: 3px;'>{$details['desc']}</div>
					<div style='float:right; margin-right: {$MARGIN_RIGHT}px; margin-bottom: 2px; margin-top:4px; border:0px;'>{$details['type']}</div>
					</div>";
		}
		$ret .= "</div>";

		$ret .= "<div style='float:right; margin-bottom: 3px; margin-right: 3px;'><input type='button' value='Save' onclick = 'save_editor_ph($number)'></div>";


		return $ret;
	}
	
	static function changAltBanner($fields,$altBanner)
	{
		global $DESC, $TYPES, $TYPES_SH;
		$ret = '';
		if (!is_array($fields))
			return "nothing to build";

		foreach ($fields as $meta_var)
		{
			$meta_var = str_replace("{","",str_replace("}","",$meta_var));
			$meta_var = str_replace("BANNER__ALT",$altBanner,$meta_var);
			$ret .=  $meta_var;
		}
		return $ret;
	}
	
}
?>
